package com.xingda.packing.dmss.minitor.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xingda.packing.dmss.annotation.LimitRequest;
import com.xingda.packing.dmss.common.R;
import com.xingda.packing.dmss.domain.ShuntProductionLine;
import com.xingda.packing.dmss.enums.AlarmTriggerType;
import com.xingda.packing.dmss.enums.TaskState;
import com.xingda.packing.dmss.minitor.entity.PkAction;
import com.xingda.packing.dmss.minitor.mapper.PkActionMapper;
import com.xingda.packing.dmss.task.ticket.AbstractTaskTicket;
import com.xingda.packing.dmss.task.ticket.ScanCodeTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@RequestMapping("/api/product")
@Slf4j
public class ProductController {
    @Resource
    private ShuntProductionLine shuntProductionLine;
    @Resource
    private PkActionMapper pkActionMapper;

    @GetMapping("/machine/{area}")
    public R rebootStatus(@PathVariable int area) {
        JSONObject jsonObject = new JSONObject();
        if (area == 0) {
            //运行状态
            jsonObject.put("status", shuntProductionLine.isInitRunning());
            AbstractTaskTicket taskTicket = shuntProductionLine.getTaskTicket();
            //任务类型
            jsonObject.put("taskType", taskTicket.getType().getTypeName());
            //任务状态
            jsonObject.put("taskStatus", taskTicket.getState().getTypeName());
            jsonObject.put("isAlreadyPacking", shuntProductionLine.getPackProductionLine().getRobot().getAlreadyPackingStatus(area));
        } else {
            jsonObject.put("status", shuntProductionLine.getPackProductionLine().initRunning(area));
            AbstractTaskTicket taskTicket = shuntProductionLine.getPackProductionLine().getRobot().getTaskTicket(area);
            //任务类型
            jsonObject.put("taskType", taskTicket.getType().getTypeName());
            //任务状态
            jsonObject.put("taskStatus", taskTicket.getState().getTypeName());
            //是否有轮
            jsonObject.put("wheel", shuntProductionLine.getPackProductionLine().getRobot().haveWheel(area));
            //是否可下发任务
            jsonObject.put("assignTask", shuntProductionLine.getPackProductionLine().getRobot().canAssignTask(area));
            //抓取位是否有轮
            jsonObject.put("is100HaveWheel", shuntProductionLine.getPackProductionLine().getRobot().is100HaveWheel(area));
            //码垛完成
            jsonObject.put("palletizingComplete", shuntProductionLine.getPackProductionLine().getRobot().isPalletizingComplete(area));
            //抓取完成
            jsonObject.put("grabComplete", shuntProductionLine.getPackProductionLine().getRobot().isGrabComplete(area));
            //重复装箱
            jsonObject.put("isAlreadyPacking", shuntProductionLine.getPackProductionLine().getRobot().getAlreadyPackingStatus(area));
        }
        return R.ok().put("data", jsonObject);
    }

    @LimitRequest(count = 1)
    @GetMapping("/setRun/{area}")
    public R setRun(@PathVariable int area) {
        try {
            if (area == 0) {
                shuntProductionLine.stopTask();
                shuntProductionLine.setInitRunning(true);
                shuntProductionLine.setCodeErrorNum(0);
                shuntProductionLine.setSnapErrorNum(0);
                shuntProductionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.SHUNT_AREA_CODE_ERROR_MORE_THAN_THREE, false, 3);
                shuntProductionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.SHUNT_AREA_SNAP_ERROR_MORE_THAN_THREE, false, 3);
                log.info("开启分流区");
            } else {
                shuntProductionLine.getPackProductionLine().setInitRunning(area, true);
                shuntProductionLine.getPackProductionLine().getRobot().setWorkStatus(true, area);
                log.info("开启装箱区,区域{}", area);
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    @LimitRequest(count = 1)
    @GetMapping("/cancel/{area}")
    public R cancel(@PathVariable int area) {
        shuntProductionLine.getPackProductionLine().getRobot().setAlreadyPackingStatus(area, false);
        return R.ok();
    }

    @LimitRequest(count = 1)
    @GetMapping("/setStop/{area}")
    public R setStop(@PathVariable int area) {
        try {
            if (area == 0) {
                shuntProductionLine.setInitRunning(false);
                log.info("停止分流区");
            } else {
                shuntProductionLine.getPackProductionLine().setInitRunning(area, false);
                log.info("停止装箱区,区域{}", area);
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    @LimitRequest(count = 1)
    @GetMapping("/setRobotNoWheel/{area}")
    public R setRobotNoWheel(@PathVariable int area) {
        try {
            LambdaQueryWrapper<PkAction> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PkAction::getArea, area);
            lambdaQueryWrapper.eq(PkAction::getFinishState, 1);
            PkAction pkAction = pkActionMapper.selectOne(lambdaQueryWrapper);
            if (Objects.nonNull(pkAction)) {
                return R.error("当前存在未完成的任务,初始化失败!请去后台管理页面:[操作管理-动作操作],确认完毕再进行初始化");
            }
            shuntProductionLine.getPackProductionLine().getRobot().clear(area);
            shuntProductionLine.getPackProductionLine().getRobot().resetStatus(area);
            log.info("设置机器人为无工字轮,区域{}", area);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    @LimitRequest(count = 1)
    @GetMapping("/resetRobot/{area}")
    public R resetRobot(@PathVariable int area) {
        try {
            if (area == 0) {
                shuntProductionLine.setCodeErrorNum(0);
                shuntProductionLine.setSnapErrorNum(0);
                shuntProductionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.SHUNT_AREA_CODE_ERROR_MORE_THAN_THREE, false, 3);
                shuntProductionLine.getEventCreater().createTriggerAlarm(AlarmTriggerType.SHUNT_AREA_SNAP_ERROR_MORE_THAN_THREE, false, 3);
                shuntProductionLine.stopTask();
                log.info("重置分流区任务");
            } else {
                LambdaQueryWrapper<PkAction> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(PkAction::getArea, area);
                lambdaQueryWrapper.eq(PkAction::getFinishState, 1);
                PkAction pkAction = pkActionMapper.selectOne(lambdaQueryWrapper);
                if (Objects.nonNull(pkAction)) {
                    return R.error("当前存在未完成的任务,初始化失败!请去后台管理页面:[操作管理-动作操作],确认完毕再进行初始化");
                }
                ScanCodeTicket scanCodeTicket = new ScanCodeTicket();
                scanCodeTicket.setState(TaskState.FINISH);
                scanCodeTicket.setLocationNo(100);
                shuntProductionLine.getPackProductionLine().getRobot().setTaskTicket(scanCodeTicket, area);
                shuntProductionLine.getPackProductionLine().getRobot().clear(area);
                shuntProductionLine.getPackProductionLine().getRobot().resetStatus(area);
                shuntProductionLine.getPackProductionLine().getRobot().setWorkStatus(true, area);
                log.info("重置装箱区任务,区域{}", area);
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }
}
